package liuwanghui.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import liuwanghui.common.PageResult;
import liuwanghui.constant.OrderStatusConstant;
import liuwanghui.dto.request.*;
import liuwanghui.dto.request.StockLogDTO;
import liuwanghui.exception.BusinessException;
import liuwanghui.mapper.ConsumerMapper;
import liuwanghui.pojo.Inventory;
import liuwanghui.pojo.Order;
import liuwanghui.pojo.Product;
import liuwanghui.pojo.Result;
import liuwanghui.service.ConsumerService;
import liuwanghui.util.CacheUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class ConsumerServiceImpl implements ConsumerService {

    private final ConsumerMapper consumerMapper;
    private final CacheUtil cacheUtil;

    // 生成订单号
    private String generateOrderNo() {
        // 格式：年月日时分秒+4位随机数
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))
                + String.format("%04d", (int)(Math.random() * 10000));
    }

    @Override
    public Result getMarketProducts(MarketQueryDTO params) {
        PageHelper.startPage(params.getPage(), params.getPageSize());
        List<Product> products = consumerMapper.findMarketProducts(params);
        return Result.success(new PageResult<>(new PageInfo<>(products).getTotal(), products));
    }

    @Override
    public Result getProductDetail(Long id) {
        Product product = consumerMapper.findProductById(id);
        if (product == null) {
            throw new BusinessException("商品不存在");
        }
        return Result.success(product);
    }

    @Override
    @Transactional
    public Result createOrder(ConsumerOrderCreateDTO dto) {
        try {
            // 1. 检查商品是否存在
            Product product = consumerMapper.findProductById(dto.getProductId());
            if (product == null) {
                throw new BusinessException("商品不存在");
            }

            // 2. 检查库存
            Inventory inventory = consumerMapper.findInventoryByProductId(dto.getProductId());
            if (inventory == null || inventory.getCurrentStock() < dto.getQuantity()) {
                throw new BusinessException("库存不足");
            }

            // 3. 建订单
            Order order = new Order();
            order.setOrderNo(generateOrderNo());  // 生成订单号
            order.setProductId(dto.getProductId());
            order.setQuantity(dto.getQuantity());
            order.setUnitPrice(product.getPrice());
            order.setTotalAmount(product.getPrice().multiply(BigDecimal.valueOf(dto.getQuantity())));
            order.setStatus(OrderStatusConstant.PENDING);
            order.setCustomerName(dto.getCustomerName());
            order.setRemark(dto.getRemark());
            consumerMapper.insertOrder(order);

            // 4. 扣减库存
            int oldStock = inventory.getCurrentStock();
            inventory.setCurrentStock(oldStock - dto.getQuantity());
            consumerMapper.updateInventoryStock(inventory);

            // 5. 记录库存变更日志
            StockLogDTO log = new StockLogDTO();
            log.setInventoryId(inventory.getId());
            log.setOldStock(oldStock);
            log.setNewStock(inventory.getCurrentStock());
            log.setChangeQuantity(-dto.getQuantity());  // 负数表示库存减少
            log.setOperator(dto.getCustomerName());
            log.setRemark("订单创建: " + order.getOrderNo());
            consumerMapper.insertStockLog(log);

            return Result.success(order);
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("创建订单失败", e);
            throw new BusinessException("创建订单失败");
        }
    }

    @Override
    public Result getDashboardStats(String timeRange, Boolean includeOrders, Boolean includeExpenses,
                                  Boolean includeFavorites, Boolean includeCategories) {
        Map<String, Object> stats = new HashMap<>();
        Long userId = cacheUtil.getCurrentUserId();

        if (Boolean.TRUE.equals(includeOrders)) {
            stats.put("orders", consumerMapper.getOrderStats(userId, timeRange));
        }
        if (Boolean.TRUE.equals(includeExpenses)) {
            stats.put("expenses", consumerMapper.getExpenseStats(userId, timeRange));
        }
        if (Boolean.TRUE.equals(includeFavorites)) {
            stats.put("favorites", consumerMapper.getFavoriteStats(userId));
        }
        if (Boolean.TRUE.equals(includeCategories)) {
            stats.put("categories", consumerMapper.getCategoryStats(userId, timeRange));
        }

        return Result.success(stats);
    }
} 